package com.cyx.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class CountUserListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        //通过Session 可以找到 Servlet 进而可以找到上下文
        ServletContext ctx = se.getSession().getServletContext();
        Lock lock = new ReentrantLock();
        lock.lock();
        try{
            Integer onLineCount = (Integer) ctx.getAttribute("onLineCount");
            if (onLineCount==null){
                onLineCount = 1;
            }else {
                onLineCount += 1;
            }
            System.out.println("onLineCount="+onLineCount);
            ctx.setAttribute("onLineCount",onLineCount);
        }finally {
            lock.unlock();
        }

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext ctx = se.getSession().getServletContext();
        Lock lock = new ReentrantLock();
        lock.lock();
        try{
            Integer onLineCount = (Integer) ctx.getAttribute("onLineCount");
            if (onLineCount==null){
                onLineCount = 0;
            }else {
                onLineCount -= 1;
            }
            System.out.println(" -- onLineCount="+onLineCount);
            ctx.setAttribute("onLineCount",onLineCount);
        }finally {
            lock.unlock();
        }
    }
}
